package chaoyue.study.runner;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 在容器启动的时候通过api的方式直接设置默认的熔断/限流规则
 */
@Component
public class InitRuleRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        initDegradeRule();
    }

    // 初始化熔断规则
    private static void initDegradeRule(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource("depart-list"); // 资源名称
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);// 指定熔断策略为慢调用比例
        degradeRule.setCount(200);// 指定最大RT
        degradeRule.setSlowRatioThreshold(0.2);// 设置比例阈值
        degradeRule.setStatIntervalMs(1000);// 设置统计时长
        degradeRule.setMinRequestAmount(2);// 设置最小请求数
        rules.add(degradeRule);
        DegradeRuleManager.loadRules(rules);
    }
}
